<template>
  <div class="task-list">
    <!-- 筛选和搜索区域 -->
    <div class="filter-section">
      <div class="filter-left">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索任务名称..."
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
      
      <div class="filter-right">
        <el-select v-model="typeFilter" placeholder="任务类型" @change="handleFilter">
          <el-option label="全部类型" value="" />
          <el-option label="视频学习" value="video" />
          <el-option label="实践练习" value="practice" />
          <el-option label="项目实战" value="project" />
          <el-option label="理论学习" value="theory" />
        </el-select>
        
        <el-select v-model="difficultyFilter" placeholder="难度" @change="handleFilter">
          <el-option label="全部难度" value="" />
          <el-option label="简单" value="简单" />
          <el-option label="中等" value="中等" />
          <el-option label="困难" value="困难" />
        </el-select>
        
        <el-select v-model="statusFilter" placeholder="状态" @change="handleFilter">
          <el-option label="全部状态" value="" />
          <el-option label="未开始" value="not_started" />
          <el-option label="进行中" value="in_progress" />
          <el-option label="已完成" value="completed" />
        </el-select>
        
        <el-select v-model="sortBy" placeholder="排序" @change="handleSort">
          <el-option label="默认排序" value="default" />
          <el-option label="难度升序" value="difficulty_asc" />
          <el-option label="难度降序" value="difficulty_desc" />
          <el-option label="时长升序" value="time_asc" />
          <el-option label="时长降序" value="time_desc" />
        </el-select>
      </div>
    </div>

    <!-- 任务统计 -->
    <div class="task-stats">
      <div class="stats-container">
        <div class="stat-item">
          <div class="stat-number">{{ filteredTasks.length }}</div>
          <div class="stat-label">任务总数</div>
        </div>
        <div class="stat-item">
          <div class="stat-number">{{ completedCount }}</div>
          <div class="stat-label">已完成</div>
        </div>
        <div class="stat-item">
          <div class="stat-number">{{ inProgressCount }}</div>
          <div class="stat-label">进行中</div>
        </div>
        <div class="stat-item">
          <div class="stat-number">{{ Math.round(completedCount / filteredTasks.length * 100) }}%</div>
          <div class="stat-label">完成率</div>
        </div>
      </div>
    </div>

    <!-- 任务列表 -->
    <div class="tasks-container">
      <div class="view-toggle">
        <el-radio-group v-model="viewMode" @change="handleViewModeChange">
          <el-radio-button label="grid">
            <el-icon><Grid /></el-icon>
            卡片视图
          </el-radio-button>
          <el-radio-button label="list">
            <el-icon><List /></el-icon>
            列表视图
          </el-radio-button>
        </el-radio-group>
      </div>
      
      <!-- 卡片视图 -->
      <div v-if="viewMode === 'grid'" class="tasks-grid">
        <div 
          v-for="task in paginatedTasks" 
          :key="task.id"
          class="task-card"
          :class="{ completed: task.status === 'completed' }"
          @click="viewTask(task)"
        >
          <div class="task-header">
            <div class="task-type">
              <el-tag :type="getTaskTypeColor(task.type)" size="small">
                {{ getTaskTypeName(task.type) }}
              </el-tag>
            </div>
            <div class="task-status">
              <el-icon v-if="task.status === 'completed'" class="completed-icon">
                <CircleCheck />
              </el-icon>
              <el-icon v-else-if="task.status === 'in_progress'" class="progress-icon">
                <Loading />
              </el-icon>
              <el-icon v-else class="pending-icon">
                <Clock />
              </el-icon>
            </div>
          </div>
          
          <div class="task-content">
            <h3 class="task-title">{{ task.title }}</h3>
            <p class="task-description">{{ task.description }}</p>
            
            <div class="task-meta">
              <div class="meta-item">
                <el-icon><Clock /></el-icon>
                <span>{{ task.estimatedTime }}分钟</span>
              </div>
              <div class="meta-item">
                <el-icon><Star /></el-icon>
                <span>{{ task.difficulty }}</span>
              </div>
            </div>
            
            <div class="task-progress" v-if="task.progress !== undefined">
              <div class="progress-info">
                <span>进度：{{ task.progress }}%</span>
              </div>
              <el-progress 
                :percentage="task.progress" 
                :show-text="false"
                :stroke-width="6"
              />
            </div>
          </div>
          
          <div class="task-footer">
            <el-button 
              :type="getButtonType(task.status)" 
              size="small"
              @click.stop="handleTaskAction(task)"
            >
              {{ getButtonText(task.status) }}
            </el-button>
          </div>
        </div>
      </div>
      
      <!-- 列表视图 -->
      <div v-else class="tasks-table">
        <el-table :data="paginatedTasks" style="width: 100%" @row-click="viewTask">
          <el-table-column width="60" align="center">
            <template #default="{ row }">
              <div class="status-indicator">
                <el-icon v-if="row.status === 'completed'" class="completed">
                  <CircleCheck />
                </el-icon>
                <el-icon v-else-if="row.status === 'in_progress'" class="progress">
                  <Loading />
                </el-icon>
                <div v-else class="not-started"></div>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column prop="title" label="任务名称" min-width="200">
            <template #default="{ row }">
              <div class="task-title-cell">
                <div class="title">{{ row.title }}</div>
                <div class="description">{{ row.description }}</div>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column prop="type" label="类型" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="getTaskTypeColor(row.type)" size="small">
                {{ getTaskTypeName(row.type) }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="difficulty" label="难度" width="80" align="center">
            <template #default="{ row }">
              <el-tag :type="getDifficultyColor(row.difficulty)" size="small">
                {{ row.difficulty }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="estimatedTime" label="预计时长" width="100" align="center">
            <template #default="{ row }">
              <span>{{ row.estimatedTime }}分钟</span>
            </template>
          </el-table-column>
          
          <el-table-column prop="progress" label="进度" width="120" align="center">
            <template #default="{ row }">
              <div v-if="row.progress !== undefined" class="progress-cell">
                <el-progress 
                  :percentage="row.progress" 
                  :show-text="false"
                  :stroke-width="6"
                />
                <span class="progress-text">{{ row.progress }}%</span>
              </div>
              <span v-else>-</span>
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="200" align="center">
            <template #default="{ row }">
              <div class="action-buttons">
                <el-button size="small" @click.stop="viewTask(row)">
                  查看详情
                </el-button>
                <el-button 
                  size="small" 
                  :type="getButtonType(row.status)"
                  @click.stop="handleTaskAction(row)"
                >
                  {{ getButtonText(row.status) }}
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <!-- 分页 -->
      <div class="pagination-container" v-if="filteredTasks.length > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[12, 24, 48, 96]"
          :total="filteredTasks.length"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      
      <!-- 空状态 -->
      <div v-if="filteredTasks.length === 0" class="empty-state">
        <EmptyState
          image="/images/empty-tasks.svg"
          title="暂无任务"
          description="当前筛选条件下没有找到相关任务"
        >
          <el-button @click="resetFilters">
            重置筛选
          </el-button>
        </EmptyState>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { 
  Search, Grid, List, CircleCheck, Loading, Clock, Star
} from '@element-plus/icons-vue'
import EmptyState from '@/components/global/EmptyState.vue'
import { ElMessage } from 'element-plus'

const router = useRouter()

// 响应式数据
const searchKeyword = ref('')
const typeFilter = ref('')
const difficultyFilter = ref('')
const statusFilter = ref('')
const sortBy = ref('default')
const viewMode = ref('grid')
const currentPage = ref(1)
const pageSize = ref(12)

// 任务数据
const tasks = ref([
  {
    id: 1,
    title: 'JavaScript基础语法',
    description: '学习JavaScript的基本语法和数据类型',
    type: 'video',
    difficulty: '简单',
    estimatedTime: 30,
    status: 'in_progress',
    progress: 75
  },
  {
    id: 2,
    title: 'HTML结构设计',
    description: '掌握HTML标签的使用和页面结构设计',
    type: 'practice',
    difficulty: '简单',
    estimatedTime: 45,
    status: 'completed',
    progress: 100
  },
  {
    id: 3,
    title: 'CSS样式布局',
    description: '学习CSS布局技巧和响应式设计',
    type: 'project',
    difficulty: '中等',
    estimatedTime: 60,
    status: 'in_progress',
    progress: 30
  },
  // 添加更多任务数据...
  ...Array.from({ length: 47 }, (_, i) => ({
    id: i + 4,
    title: `学习任务 ${i + 4}`,
    description: `这是第${i + 4}个学习任务的描述`,
    type: ['video', 'practice', 'project', 'theory'][Math.floor(Math.random() * 4)],
    difficulty: ['简单', '中等', '困难'][Math.floor(Math.random() * 3)],
    estimatedTime: Math.floor(Math.random() * 120) + 30,
    status: ['not_started', 'in_progress', 'completed'][Math.floor(Math.random() * 3)],
    progress: Math.random() > 0.5 ? Math.floor(Math.random() * 100) : undefined
  }))
])

// 计算属性
const filteredTasks = computed(() => {
  let filtered = tasks.value

  // 搜索筛选
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(task => 
      task.title.toLowerCase().includes(keyword) ||
      task.description.toLowerCase().includes(keyword)
    )
  }

  // 类型筛选
  if (typeFilter.value) {
    filtered = filtered.filter(task => task.type === typeFilter.value)
  }

  // 难度筛选
  if (difficultyFilter.value) {
    filtered = filtered.filter(task => task.difficulty === difficultyFilter.value)
  }

  // 状态筛选
  if (statusFilter.value) {
    filtered = filtered.filter(task => task.status === statusFilter.value)
  }

  // 排序
  switch (sortBy.value) {
    case 'difficulty_asc':
      filtered.sort((a, b) => {
        const order = { '简单': 1, '中等': 2, '困难': 3 }
        return order[a.difficulty] - order[b.difficulty]
      })
      break
    case 'difficulty_desc':
      filtered.sort((a, b) => {
        const order = { '简单': 1, '中等': 2, '困难': 3 }
        return order[b.difficulty] - order[a.difficulty]
      })
      break
    case 'time_asc':
      filtered.sort((a, b) => a.estimatedTime - b.estimatedTime)
      break
    case 'time_desc':
      filtered.sort((a, b) => b.estimatedTime - a.estimatedTime)
      break
    default: // default
      filtered.sort((a, b) => a.id - b.id)
  }

  return filtered
})

const paginatedTasks = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredTasks.value.slice(start, end)
})

const completedCount = computed(() => {
  return filteredTasks.value.filter(task => task.status === 'completed').length
})

const inProgressCount = computed(() => {
  return filteredTasks.value.filter(task => task.status === 'in_progress').length
})

// 方法
const getTaskTypeColor = (type) => {
  const colors = {
    'video': 'primary',
    'practice': 'success',
    'project': 'warning',
    'theory': 'info'
  }
  return colors[type] || 'default'
}

const getTaskTypeName = (type) => {
  const names = {
    'video': '视频学习',
    'practice': '实践练习',
    'project': '项目实战',
    'theory': '理论学习'
  }
  return names[type] || '未知'
}

const getDifficultyColor = (difficulty) => {
  const colors = {
    '简单': 'success',
    '中等': 'warning',
    '困难': 'danger'
  }
  return colors[difficulty] || 'info'
}

const getButtonType = (status) => {
  const types = {
    'completed': 'success',
    'in_progress': 'warning',
    'not_started': 'primary'
  }
  return types[status] || 'default'
}

const getButtonText = (status) => {
  const texts = {
    'completed': '已完成',
    'in_progress': '继续学习',
    'not_started': '开始学习'
  }
  return texts[status] || '开始学习'
}

const handleSearch = () => {
  currentPage.value = 1
}

const handleFilter = () => {
  currentPage.value = 1
}

const handleSort = () => {
  currentPage.value = 1
}

const handleViewModeChange = () => {
  // 切换视图模式时调整分页大小
  if (viewMode.value === 'grid') {
    pageSize.value = 12
  } else {
    pageSize.value = 20
  }
  currentPage.value = 1
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page) => {
  currentPage.value = page
}

const resetFilters = () => {
  searchKeyword.value = ''
  typeFilter.value = ''
  difficultyFilter.value = ''
  statusFilter.value = ''
  sortBy.value = 'default'
  currentPage.value = 1
}

const viewTask = (task) => {
  router.push(`/task/detail/${task.id}`)
}

const handleTaskAction = (task) => {
  if (task.status === 'completed') {
    ElMessage.info('任务已完成')
  } else {
    startTask(task)
  }
}

const startTask = (task) => {
  router.push(`/task/learn/${task.id}`)
}

onMounted(() => {
  // 初始化数据
})
</script>

<style lang="scss" scoped>
.task-list {
  min-height: 100vh;
  background: var(--el-bg-color-page);
  padding: 20px;
}

.filter-section {
  background: white;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  @media (max-width: 1024px) {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
}

.filter-left {
  .el-input {
    width: 300px;
    
    @media (max-width: 1024px) {
      width: 100%;
    }
  }
}

.filter-right {
  display: flex;
  gap: 12px;
  
  @media (max-width: 1024px) {
    flex-wrap: wrap;
  }
  
  .el-select {
    width: 120px;
    
    @media (max-width: 768px) {
      flex: 1;
      min-width: 100px;
    }
  }
}

.task-stats {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  margin-bottom: 20px;
}

.stats-container {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  
  @media (max-width: 768px) {
    grid-template-columns: repeat(2, 1fr);
  }
}

.stat-item {
  text-align: center;
  
  .stat-number {
    font-size: 24px;
    font-weight: 700;
    color: var(--el-color-primary);
    margin-bottom: 4px;
  }
  
  .stat-label {
    font-size: 12px;
    color: var(--el-text-color-secondary);
  }
}

.tasks-container {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}

.view-toggle {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
}

.tasks-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.task-card {
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 8px;
  padding: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
  }
  
  &.completed {
    background: var(--el-color-success-light-9);
    border-color: var(--el-color-success-light-5);
  }
}

.task-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.task-status {
  .completed-icon {
    color: var(--el-color-success);
    font-size: 20px;
  }
  
  .progress-icon {
    color: var(--el-color-warning);
    font-size: 20px;
  }
  
  .pending-icon {
    color: var(--el-text-color-placeholder);
    font-size: 20px;
  }
}

.task-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 8px;
  color: var(--el-text-color-primary);
}

.task-description {
  font-size: 14px;
  color: var(--el-text-color-secondary);
  margin-bottom: 16px;
  line-height: 1.5;
}

.task-meta {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
  
  .meta-item {
    display: flex;
    align-items: center;
    gap: 4px;
    font-size: 12px;
    color: var(--el-text-color-placeholder);
    
    .el-icon {
      color: var(--el-color-primary);
    }
  }
}

.task-progress {
  margin-bottom: 16px;
  
  .progress-info {
    display: flex;
    justify-content: space-between;
    margin-bottom: 8px;
    font-size: 12px;
    color: var(--el-text-color-secondary);
  }
}

.task-footer {
  text-align: right;
}

.status-indicator {
  display: flex;
  justify-content: center;
  align-items: center;
  
  .completed {
    color: var(--el-color-success);
    font-size: 18px;
  }
  
  .progress {
    color: var(--el-color-warning);
    font-size: 18px;
  }
  
  .not-started {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background: var(--el-border-color-light);
  }
}

.task-title-cell {
  .title {
    font-weight: 500;
    margin-bottom: 4px;
    color: var(--el-text-color-primary);
  }
  
  .description {
    font-size: 12px;
    color: var(--el-text-color-placeholder);
    @include text-ellipsis(2);
  }
}

.progress-cell {
  display: flex;
  align-items: center;
  gap: 8px;
  
  .el-progress {
    flex: 1;
  }
  
  .progress-text {
    font-size: 12px;
    color: var(--el-text-color-secondary);
    min-width: 35px;
  }
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
}

:deep(.el-table) {
  .el-table__row {
    cursor: pointer;
    
    &:hover {
      background-color: var(--el-fill-color-extra-light);
    }
  }
}

@media (max-width: 768px) {
  .tasks-grid {
    grid-template-columns: 1fr;
  }
  
  .action-buttons {
    flex-direction: column;
    gap: 4px;
    
    .el-button {
      font-size: 12px;
      padding: 4px 8px;
    }
  }
  
  .view-toggle {
    justify-content: center;
  }
}
</style>
